﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ActorHpSlider : MonoBehaviour {


    public int maxHp=4;
    private Entity suiEntity;//获取主角
    private float hpLimit;//血条的上限
    private float hpValue;//获取血量
                          // Use this for initialization
    private RectTransform booldBg;//获取背景图
    private RectTransform booldBgRight;//获取右端
    private Vector3 booldPosition;//记录右端的位置
    private GameObject hpGroups;
    private GameObject[] hp=new GameObject[7];//血量
    private float[] width = { 122, 156, 190,220 };
    /// <summary>
    /// 初始化所有组件
    /// </summary>
    void Start()
    {
        booldBg = transform.GetChild(1).gameObject.GetComponent<RectTransform>();
        booldBgRight= transform.GetChild(2).gameObject.GetComponent<RectTransform>();
        booldPosition = new Vector3(0, booldBgRight.localPosition.y, booldBgRight.localPosition.z);
        hpGroups = transform.GetChild(3).gameObject;
        int i = 0;
        foreach(Transform ts in hpGroups.transform)
        {
            hp[i] = ts.gameObject;
            i++;
        }
        suiEntity = GameManager.Instance.Sui.gameObject.GetComponent<Entity>();
        if (suiEntity != null)
        {
            hpLimit = suiEntity.HpLimit;
            hpValue = suiEntity.Hp;
        }
        for (i = i - 1; i >= hpLimit; i--)
        {
            hp[i].SetActive(false);
        }
        Modify();
        suiEntity.OnHpChange +=new System.Action<float>(ChangHpValue);
        suiEntity.OnHpLimitChange += new System.Action<float>(ChangHpLimit);

    }
    /// <summary>
    /// 改变血量
    /// </summary>
    /// <param name="value"></param>
    public void ChangHpValue(float value)
    {
        if (value < hpValue)
        {
            for(int i=(int)hpValue-1;i>=value;i--)
            hp[i].SetActive(false);
        }
        else hp[(int)value-1].SetActive(true);
        hpValue = value;
    }
    /// <summary>
    /// 改变血量上限
    /// </summary>
    /// <param name="value"></param>
    public void ChangHpLimit(float value)
    {
        if (value >= 4&&value<=maxHp) {
            hpLimit = value;
            Modify();
        }
    }//最低为4滴血
    public void Modify()
    {
        if (hpLimit >= 4)
        {
            booldBg.sizeDelta = new Vector2(width[(int)hpLimit - 4], booldBg.sizeDelta.y);
            booldBgRight.localPosition= new Vector3(width[(int)hpLimit - 4] + 20.25f, 0, 0) + booldPosition;
        }
    }
    public void OnAdd()
    {
        suiEntity.HpLimit += 1;
    }
    public void OnJ()
    {
        suiEntity.HpLimit -= 1;
    }
}
